from docx import Document
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
from docx.text.paragraph import Paragraph
from docx.oxml.shared import qn as shared_qn
import os
import sqlite3

def insert_text_after_bookmark_start(paragraph, bookmark_id, text):
    """
    在包含 bookmarkStart 的段落中插入文本。
    """
    # 获取底层 XML 元素
    p = paragraph._element
    for child in p:
        if child.tag == qn('w:bookmarkStart') and child.get(qn('w:id')) == bookmark_id:
            # 在 bookmarkStart 紧跟处插入新 run
            run = OxmlElement('w:r')
            t = OxmlElement('w:t')
            t.text = text
            run.append(t)
            p.insert(p.index(child) + 1, run)
            return True
    return False

def process_paragraphs(paragraphs, bookmark_names, cursor, project_id):
    for para in paragraphs:
        p = para._element
        for child in p:
            if child.tag == qn('w:bookmarkStart'):
                name = child.get(qn('w:name'))
                bookmark_id = child.get(qn('w:id'))
                if name and name != "_GoBack":
                    bookmark_names.append(name)
                    insert_content = ""
                    if name == "项目名称":
                        sql_select = "select project_name from doctest where project_id = ?;"
                        cursor.execute(sql_select, (project_id,))
                        results = cursor.fetchall()
                        insert_content = results[0][0] if results else ""
                    elif name == "开始时间":
                        sql_select = f"select start_time from doctest where project_id = ?;"
                        cursor.execute(sql_select, (project_id,))
                        results = cursor.fetchall()
                        insert_content = results[0][0] if results else ""
                    elif name == "主要内容":
                        sql_select = f"select addition from doctest where project_id = ?;"
                        cursor.execute(sql_select, (project_id,))
                        results = cursor.fetchall()
                        if len(results) != 0:
                            insert_content = results[0][0] if results else ""
                        else:
                            insert_content = ""
                    elif name == "参与人员":
                        sql_select = f"select user_name from project_user where project_id = ?;"
                        cursor.execute(sql_select, (project_id,))
                        results = cursor.fetchall()
                        insert_content = "，".join([result[0] for result in results]) if results else ""
                    insert_text_after_bookmark_start(para, bookmark_id, insert_content)

def process_tables(tables, bookmark_names, cursor, project_id):
    for table in tables:
        for row in table.rows:
            for cell in row.cells:
                process_paragraphs(cell.paragraphs, bookmark_names, cursor, project_id)
                process_tables(cell.tables, bookmark_names, cursor, project_id)  # 递归处理嵌套表格

def insert_text_at_bookmarks(db_path, docx_path, output_path, project_id):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    doc = Document(docx_path)
    bookmark_names = []

    # 处理文档段落
    process_paragraphs(doc.paragraphs, bookmark_names, cursor, project_id)

    # 处理表格（递归）
    process_tables(doc.tables, bookmark_names, cursor, project_id)

    # 输出书签名称
    print("书签列表：")
    for name in bookmark_names:
        print(name)

    # 保存到新文件
    doc.save(output_path)
    print(f"新文档已保存为: {output_path}")

    cursor.close()
    conn.close()

# 用法
db_path = os.path.join(os.getcwd(), "test.db")
docx_path = os.path.join(os.getcwd(), "test.docx")
docx_gen_path = os.path.join(os.getcwd(), "test_gen.docx")
insert_text_at_bookmarks(db_path, docx_path, docx_gen_path, "000001")